package xiaojian.toolkit.netty.handler.codec.http.transformer;

import io.netty.handler.codec.http.FullHttpRequest;

import java.util.List;

import org.apache.commons.collections4.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.bean.event.EventTypeMetainfo;
import xiaojian.toolkit.ebus.EventBus;

public class FireMultiEventTransformer2 implements
		HttpRequestTransformer {
	
	private static final Logger logger = LoggerFactory.getLogger(FireMultiEventTransformer2.class);

	private EventBus eventBus;
	private EventTypeMetainfo eventTypeMetainfo = null;

	/**
	 * @param event
	 *            the event to set
	 */
	public void setEventTypeMetainfo(EventTypeMetainfo eventTypeMetainfo) {
		this.eventTypeMetainfo = eventTypeMetainfo;
	}

	/**
	 * @return the eventBus
	 */
	public EventBus getEventBus() {
		return eventBus;
	}

	/**
	 * @param eventBus
	 *            the eventBus to set
	 */
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	}

	/**
	 * @return the impl
	 */
	public Transformer getImpl() {
		return impl;
	}

	/**
	 * @param impl
	 *            the impl to set
	 */
	public void setImpl(Transformer impl) {
		this.impl = impl;
	}

	private Transformer impl;

	@Override
	public Object transform(FullHttpRequest from) {
		Object bean = impl.transform(from);

		if (null != bean) {
			List<String> events = eventTypeMetainfo.find(bean.getClass());
			if (events == null || events.size() == 0) {
				throw new RuntimeException("Cannot get event by class["
						+ bean.getClass().getName() + "].");
			}

			for (String event : events) {
				if(!eventBus.fireEvent(event, bean)) {
					logger.warn("Event bus is busy. event[{}], bean[{}].", event, bean);
					throw new HttpTransformException(503, "SERVER_BUSY");
				}
			}
		}
		return bean;
	}
}
